<template>
	<div class="personnelAdd">
		<!-- <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/' }"><i class="lh lh-diaodu fw_100"></i></el-breadcrumb-item>
            <el-breadcrumb-item :to="{ path: '/merchantsList' }">B端-商户</el-breadcrumb-item>
            <el-breadcrumb-item :to="{ path: '/merchantsList' }">商户管理</el-breadcrumb-item>
            <el-breadcrumb-item>新增商户</el-breadcrumb-item>
        </el-breadcrumb> -->
		<el-breadcrumb separator="/">
			<el-breadcrumb-item :to="{ path: '/dataExpress' }"><i class="lh fw_300 lh-seller"></i></el-breadcrumb-item>
			<el-breadcrumb-item>B端-商户</el-breadcrumb-item>
			<el-breadcrumb-item>新增商户</el-breadcrumb-item>
		</el-breadcrumb>
		<div class="content_Box box-shadow mt_15 px_10">
			<el-tabs type="border-card">
				<el-tab-pane label="基本信息">
					<el-form label-width="100px" class="mw_400">
						<el-form-item label="商户名称" :required="true">
							<el-input v-model="dataMes.name"></el-input>
						</el-form-item>
						<el-form-item label="商户类型" :required="true">
							<el-radio-group v-model="dataMes.type">
								<el-radio label="1">企业</el-radio>
								<el-radio label="2">个人</el-radio>
							</el-radio-group>
						</el-form-item>

						<el-form-item label="商户负责人" :required="false">
							<el-input v-model="dataMes.merchant_name"></el-input>
						</el-form-item>
						<el-form-item label="负责人手机号" :required="false" style="position: relative;">
							<el-input v-model="dataMes.merchant_phone"></el-input>
							<small class="tips">
								(商户负责人与负责人手机号只用于信息记录，不再生成登录账号，创建账号请前往【商户账号管理】页面)
							</small>
						</el-form-item>
						<el-form-item label="所在城市" :required="true">
							<el-select v-model="city_arr" placeholder="请选择" @change="changeBtndialog">
								<el-option
									v-for="item in cityList"
									:key="item.id"
									:label="item.city_name"
									:value="`${item.id}|${item.city_name}|${item.city_sn}`"
								>
								</el-option>
							</el-select>
						</el-form-item>
						<el-form-item label="所属行业" :required="true">
							<el-select v-model="dataMes.industry">
								<el-option
									v-for="(item, index) in industryJobList"
									:key="index"
									:label="item.label_name"
									:value="item.id"
								></el-option>
							</el-select>
						</el-form-item>
						<el-form-item label="联系地址">
							<el-input v-model="dataMes.address"></el-input>
						</el-form-item>
						<el-form-item label="电子邮箱">
							<el-input v-model="dataMes.email"></el-input>
						</el-form-item>
						<el-form-item label="销售" :required="true">
							<el-autocomplete
								class="inline-input"
								v-model="dataMes.bd_name"
								:fetch-suggestions="querySearch"
								placeholder="请输入"
								:trigger-on-focus="true"
								@select="handleSelect"
							></el-autocomplete>
						</el-form-item>
						<el-form-item label="联系电话">
							<el-input v-model="dataMes.bd_phone" disabled></el-input>
						</el-form-item>
						<el-form-item class="my_20">
							<el-button round type="primary" @click="submitBtn">立即创建</el-button>
							<el-button round @click="back">返回</el-button>
						</el-form-item>
					</el-form>
				</el-tab-pane>
				<!-- 灵活管家权限 -->
				<el-tab-pane label="灵活管家权限">
					<div class="pt_10">
						<div class="row-info clear">
							<div class="fl title-key"><i class="lhadmin lhadmin-wujiaoxing"></i>灵活管家</div>
							<div class="fl list-cont">
								<el-radio-group v-model="housekeeper.is_lh_housekeeper">
									<el-radio label="2">关闭</el-radio>
									<el-radio label="1">开通</el-radio>
								</el-radio-group>
							</div>
						</div>
						<div class="row-info clear">
							<div class="fl title-key"><i class="lhadmin lhadmin-wujiaoxing"></i>免审发薪</div>
							<div class="fl list-cont">
								<el-radio-group v-model="housekeeper.is_no_examine" disabled>
									<el-radio label="2">关闭</el-radio>
									<el-radio label="1">开通</el-radio>
								</el-radio-group>
							</div>
						</div>
						<div class="row-info clear">
							<div class="fl title-key"><i class="lhadmin lhadmin-wujiaoxing"></i>线上保险</div>
							<div class="fl list-cont">
								<el-radio-group v-model="gj_status">
									<el-radio label="1">关闭</el-radio>
									<el-radio label="2">开通</el-radio>
								</el-radio-group>
							</div>
						</div>
						<div class="row-info clear" v-show="gj_status == 2">
							<div class="fl title-key"><i class="lhadmin lhadmin-wujiaoxing"></i>线上保险</div>
							<div class="fl list-cont">
								<el-radio-group v-model="housekeeper.insurance_type">
									<el-radio label="qhbx">启航保险</el-radio>
								</el-radio-group>
							</div>
						</div>
						<div class="row-info clear">
							<div class="fl title-key"><i class="lhadmin lhadmin-wujiaoxing"></i>账单生成模式</div>
							<div class="fl list-cont">
								<el-radio-group v-model="housekeeper.bill_staff_type">
									<el-radio label="1">计薪规则</el-radio>
									<el-radio label="2">线下核算并导入</el-radio>
								</el-radio-group>
							</div>
						</div>
						<!-- v3.4结算通道-开始 -->
						<div class="row-info clear">
							<div class="fl title-key"><i class="lhadmin lhadmin-wujiaoxing"></i>结算通道</div>
							<!-- 显示默认两个字 -->
							<div class="fl list-cont">
								<el-select v-model="channelValue" @change="changeChannelList">
									<el-option
										v-for="(item, index) in channelList"
										:key="index"
										:label="item.is_default == 1 ? item.name + '（默认）' : item.name"
										:value="
											item.sn + '|' + item.company_name + '|' + item.tax_source + '|' + item.rate + '|' + item.type
										"
									></el-option>
								</el-select>
							</div>
						</div>
						<div class="row-info clear">
							<div>
								<div class="fl title-key">签约公司</div>
								<div class="fl list-cont">
									<el-input v-model="company_name" disabled></el-input>
								</div>
							</div>
							<div>
								<div class="fl title-key">税源地名称</div>
								<div class="fl list-cont">
									<el-input v-model="tax_source" disabled></el-input>
								</div>
							</div>
						</div>
						<div class="row-info clear">
							<div class="fl title-key"><i class="lhadmin lhadmin-wujiaoxing"></i>商户费率</div>
							<div class="fl list-cont feilv">
								<el-input v-model="settlement.rate" class="w_80i"></el-input>
							</div>
							<div class="fl title-key" style="width: 20px;">%</div>
						</div>
						<!-- v3.4结算通道-结束 -->
						<div class="row-info clear">
							<div class="fl title-key"><i class="lhadmin lhadmin-wujiaoxing"></i>发薪模式</div>
							<div class="fl list-cont">
								<el-radio-group v-model="housekeeper.auto_withdraw_cash">
									<el-radio label="1">银行卡</el-radio>
									<el-radio label="2">灵活儿小金库</el-radio>
								</el-radio-group>
							</div>
						</div>
						<div class="row-info clear">
							<div class="fl title-key"><i class="lhadmin lhadmin-wujiaoxing"></i>二维码</div>
							<div class="fl list-cont">
								<el-radio-group v-model="housekeeper.if_staff_bind_shop">
									<el-radio label="2">入职、签到分开</el-radio>
									<el-radio label="1">入职、签到合并</el-radio>
								</el-radio-group>
							</div>
						</div>
						<div class="row-info clear">
							<div class="fl title-key">定制域名</div>
							<div class="fl list-cont">
								<el-input v-model="housekeeper.domain_name"></el-input>
							</div>
							<div class="fl title-key" style="width: 280px;">
								（为空时使用公共域名：b.zhongfuyun.com）
							</div>
						</div>
						<div class="row-info clear">
							<div class="fl title-key">定制logo</div>
							<div class="fl list-cont">
								<uploadedit pic_name="'login_url'" :pic_url="housekeeper.login_url" @func="img5"></uploadedit>
							</div>
							<div class="fl title-key" style="width: 325px; text-align: left; margin-left: 10px;">
								(使用定制域名时生效；为空时使用默认logo：中服云logo；支持JPG、PNG的图片，尺寸大于等于600*200px）
							</div>
						</div>
					</div>
					<div class="ml_110 mt_20">
						<span class="resetBtn mr_10" @click="back">返回</span>
						<span class="btnOK" @click="submitBtn">保存</span>
					</div>
				</el-tab-pane>
			</el-tabs>
		</div>

		<!-- 是否该店铺创建账号-弹框 -->
		<el-dialog title="提示" :visible.sync="editMerchantsFlag" width="560px" :close-on-click-modal="hideEditMerchants">
			<div class="auditCentent">
				<span>商户创建成功! 是否为该商户创建账号？</span>
			</div>
			<div slot="footer" class="dialog-footer">
				<span class="btnOK mr_20" @click="goEditMerchants">创 建</span>
				<span class="resetBtn" @click="hideEditMerchants">取 消</span>
			</div>
		</el-dialog>
	</div>
</template>

<script>
var common = require('../../../static/tool.js')
import { mainfun } from '../../../assets/js/main.js'
import { fetchIndustryJob } from '@/api/label.js'
import { getListCommon } from '@/api/talent.js'

export default {
	name: 'MerchantsEdit',
	data() {
		return {
			windowSizeHeight: document.documentElement.clientHeight, //浏览器可视化窗口的大小
			screenHeight: document.documentElement.clientHeight,
			manageInfo: JSON.parse(sessionStorage.getItem('manageInfo')), //登录信息
			url: common.url,
			cityList: [], //城市列表
			//相关数据
			dataMes: {
				type: '',
				name: '',
				merchant_name: '',
				merchant_phone: '',
				industry: '',
				city_sn: '',
				city_id: '',
				city_name: '',
				address: '',
				email: '',
				bd_name: '',
				bd_userid: '',
				bd_phone: ''
			},
			city_arr: '',
			city_id: '',
			city_name: '',
			city_sn: '',
			BusinessUserList: [], //销售列表
			housekeeper: {
				is_lh_housekeeper: '',
				is_no_examine: '2',
				insurance_type: '',
				bill_staff_type: '',
				auto_withdraw_cash: '',
				if_staff_bind_shop: '',
				domain_name: '',
				login_url: ''
			},
			settlement: {
				sn: '',
				rate: ''
			},
			gj_status: '',
			industryJobList: [],
			channelList: [],
			channelValue: '',
			company_name: '',
			tax_source: '',
			rate: 0,
			editMerchantsFlag: false, // 新增时判断是否修改
			editBusiness_sn: '',
			editBusiness_id: ''
		}
	},

	mounted() {
		this.getBusinessUser()
		this.getcityList()
		this.getChannelList() // 结算通道列表
	},
	methods: {
		//获取销售列表
		getBusinessUser() {
			let fn = new FormData()
			this.$http.post(this.url + '/manageUser/getBusinessUser', fn).then(
				res => {
					// console.log(res.data.data);
					if (res.data.msg == '查询成功!' || res.data.code == '200') {
						if (res.data.data != null) {
							res.data.data.forEach(item => {
								item.value = item.nickname
							})
							this.BusinessUserList = res.data.data
						} else {
							this.BusinessUserList = []
						}
					} else if (res.data.code == '8886') {
						//code   8886  登录过期
						sessionStorage.clear()
						this.$alert('登录已过期，请重新登录 !', '提示', {
							confirmButtonText: '确定',
							callback: action => {
								window.location = 'login.html'
							}
						})
						return
					} else {
						this.$message.error(res.data.msg)
						return
					}
				},
				res => {
					this.$message.error('网络错误！')
					return
				}
			)
		},
		submitBtn() {
			// 新增接口
			if (this.dataMes.type == undefined || this.dataMes.name == undefined) {
				this.$message.error('请填写必填项')
				return
			}

			//判断销售是否存在 this.dataMes.bd_name
			var existence = false //默认不存在
			this.BusinessUserList.forEach(item => {
				if (this.dataMes.bd_name == item.nickname) {
					existence = true
				}
			})
			if (existence == false) {
				this.$message.error('请选择正确的销售')
				return
			}
			if (this.housekeeper.is_lh_housekeeper == 1) {
				// 开通才会进行校验
				if (
					!this.housekeeper.is_lh_housekeeper ||
					// !this.housekeeper.is_no_examine ||
					!this.housekeeper.bill_staff_type ||
					!this.housekeeper.auto_withdraw_cash ||
					!this.housekeeper.if_staff_bind_shop ||
					!this.settlement.sn ||
					!this.settlement.rate
				) {
					this.$message.error('灵活管家权限必填项不可为空！')
					return
				}

				if (+this.settlement.rate < +this.rate) {
					this.$message.error('费率不得小于对应结算通道设置的费率！')
					return
				}

				if (!this.housekeeper.insurance_type && this.gj_status == 2) {
					this.$message.error('灵活管家权限必填项不可为空！')
					return
				}
			}

			let fn = new FormData()

			fn.append('type', this.dataMes.type)
			fn.append('name', this.dataMes.name)
			fn.append('merchant_name', this.dataMes.merchant_name)
			fn.append('merchant_phone', this.dataMes.merchant_phone)
			fn.append('industry', this.dataMes.industry)
			fn.append('city_sn', this.city_sn)
			fn.append('city_id', this.city_id)
			fn.append('city_name', this.city_name)
			fn.append('address', this.dataMes.address)
			fn.append('email', this.dataMes.email)
			fn.append('bd_name', this.dataMes.bd_name)
			fn.append('bd_userid', this.dataMes.bd_userid)
			fn.append('bd_phone', this.dataMes.bd_phone)
			fn.append(
				'config',
				JSON.stringify({
					housekeeper: {
						...this.housekeeper,
						settlement: {
							settlement_channel_sn: this.settlement.sn,
							rate: +this.settlement.rate / 100
						}
					}
				})
			)
			this.$http.post(this.url + '/business/add', fn).then(
				res => {
					if (res.data.msg == '新增成功' || res.data.code == '200') {
						this.editMerchantsFlag = true
						this.editBusiness_sn = res.data.data.business_sn
						this.editBusiness_id = res.data.data.id
						// this.$message.success('创建成功！')
						// this.back()
					} else if (res.data.code == '8886') {
						//code   8886  登录过期
						sessionStorage.clear()
						this.$alert('登录已过期，请重新登录 !', '提示', {
							confirmButtonText: '确定',
							callback: action => {
								window.location = 'login.html'
							}
						})
						return
					} else {
						this.$message.error(res.data.msg)
						return
					}
				},
				res => {
					this.$message.error('网络错误！')
					return
				}
			)
		},
		getcityList() {
			//获取城市列表
			let fn = new FormData()
			this.$http.post(this.url + '/city/list', fn).then(
				res => {
					if (res.data.msg == '查询成功' || res.data.code == '200') {
						this.cityList = res.data.data.list
					} else if (res.data.code == '8886') {
						//code   8886  登录过期
						sessionStorage.clear()
						this.$alert('登录已过期，请重新登录 !', '提示', {
							confirmButtonText: '确定',
							callback: action => {
								window.location = 'login.html'
							}
						})
						return
					} else {
						this.$message.error(res.data.msg)
						return
					}
				},
				res => {
					this.$message.error('网络错误！')
					return
				}
			)
		},
		changeBtndialog() {
			let [id, name, code] = this.city_arr.split('|') // es6 数组解构赋值
			this.city_id = id.toString()
			this.city_name = name.toString()
			this.city_sn = code.toString()
			this.dataMes.industry = ''
			this.getIndustryJob()
		},
		back() {
			//返回
			this.$router.go(-1)
		},
		//自动完成
		querySearch(queryString, cb) {
			var restaurants = this.BusinessUserList
			var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants
			// 调用 callback 返回建议列表的数据
			cb(results)
		},
		createFilter(queryString) {
			return restaurant => {
				return restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
			}
		},
		handleSelect(item) {
			console.log(item)
			this.dataMes.bd_name = item.nickname
			this.dataMes.bd_userid = item.user_id
			this.dataMes.bd_phone = item.mobile
		},
		img5(data) {
			this.housekeeper.login_url = data
		},
		async getIndustryJob() {
			try {
				let ret = await fetchIndustryJob({
					city_id: this.city_id
				})

				this.industryJobList = ret
			} catch (err) {
				console.log(err)
			}
		},
		async getChannelList() {
			try {
				let ret = await getListCommon({
					status: 1,
					is_balance: 2
				})
				this.channelList = ret.list
			} catch (err) {
				// console.log(err)
			}
		},
		changeChannelList(value) {
			let [a, b, c, d, e] = value.split('|')
			this.company_name = b
			this.tax_source = c
			this.rate = this.returnFloat(d)

			this.settlement.sn = a
			this.settlement.rate = this.returnFloat(d)
			console.log(e)

			if (e == 2) {
				// 结算通道是三方，则选中银行卡
				this.housekeeper.auto_withdraw_cash = '1'
			} else {
				this.housekeeper.auto_withdraw_cash = ''
			}
		},
		returnFloat(value) {
			var value = Math.round(parseFloat(value) * 100) / 100
			var xsd = value.toString().split('.')
			if (xsd.length == 1) {
				value = value.toString() + '.00'
				return value
			}
			if (xsd.length > 1) {
				if (xsd[1].length < 2) {
					value = value.toString() + '0'
				}
				return value
			}
		},
		hideEditMerchants() {
			this.$router.go(-1)
			this.editMerchantsFlag = false
		},
		goEditMerchants() {
			this.editMerchantsFlag = false
			const { merchant_name, merchant_phone, name } = this.dataMes
			this.$router.replace(
				`/shopUserAdd?role_id=100&merchant_name=${merchant_name}&merchant_phone=${merchant_phone}&name=${name}&business_sn=${this.editBusiness_sn}&business_id=${this.editBusiness_id}`
			)
		}
	},
	filters: {}
}
</script>

<style scoped>
.row-info {
	margin-bottom: 10px;
}
.title-key {
	width: 100px;
}
.list-cont img {
	width: 128px;
}
.tips {
	position: absolute;
	left: 320px;
	width: 600px;
}
</style>
<style>
.feilv input {
	width: 100% !important;
}
</style>



// WEBPACK FOOTER //
// src/components/merchants/MerchantsAdd.vue